package cn.fl.dk.web.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.dk.facade.api.IDkQuestneLogApiService;
import cn.fl.dk.facade.condition.DkBillInfoQC;
import cn.fl.dk.facade.constant.DkBillInfoConstant;
import cn.fl.dk.facade.dto.DkBillInfoDTO;
import cn.fl.dk.web.service.IDkBillInfoService;
import cn.fl.dk.web.service.IDkRuleInfoService;
import cn.fl.dk.web.vo.DkBillInfoVO;
import cn.fl.dk.web.vo.DkRuleInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysDictionaryService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/dk/dkbillinfo")
public class DkBillInfoController extends BaseController {

	//private static final Logger logger = LoggerFactory.getLogger(DkBillInfoController.class);
	/**
	 * DkBillInfo 服务层BEAN
	 */
	@Autowired
	private IDkBillInfoService dkBillInfoService;
	@Autowired
	private ISysDictionaryService sysDictionaryService;
	@Autowired
    private IDkRuleInfoService dkRuleInfoService;
	@Autowired
	private IDkQuestneLogApiService dkQuestneLogApiService;
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.newLogger("加载列表页面").setLogOperType(LogOperEnum.REQ).setKeys("toListPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		ModelAndView view = new ModelAndView("dk/dkBillInfo/dkBillInfoList");
		List<String> codeGrpCdList = new ArrayList<>();
		codeGrpCdList.add(DkBillInfoConstant.CODE_DK_BILL_STS_CD);
		Map<String, List<KeyValueVO>> billStsCdList = sysDictionaryService.getMultiKvList(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), codeGrpCdList);
		view.addObject("billStsCdList",billStsCdList);
		return view;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.newLogger("加载新增页面").setLogOperType(LogOperEnum.REQ).setKeys("toAddPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		ModelAndView view = new ModelAndView("dk/dkBillInfo/dkBillInfoAdd");
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.newLogger("加载修改页面").setLogOperType(LogOperEnum.REQ).setKeys("toModifyPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("dk/dkBillInfo/dkBillInfoModify");
		view.addObject("id", id);
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.newLogger("加载详情页面").setLogOperType(LogOperEnum.REQ).setKeys("toDetailPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("dk/dkBillInfo/dkBillInfoDetail");
		view.addObject("id", id);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.newLogger("加载列表页面").setLogOperType(LogOperEnum.REQ).setKeys("initList",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String billNm = request.getParameter("billNm");//垫款单名称
		String refPrjNm = request.getParameter("refPrjNm");//再融资项目名称
		String billStsCd = request.getParameter("billStsCd");//状态
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		DkBillInfoQC qc = new DkBillInfoQC();
		if (StringUtils.isNotEmpty(billNm)) {
			qc.setBillNm(billNm);
		}
		if (StringUtils.isNotEmpty(refPrjNm)) {
			qc.setRefPrjNm(refPrjNm);
		}
		if (StringUtils.isNotEmpty(billStsCd)) {
			qc.setBillStsCd(billStsCd);
		}
		page.setCondition(qc);
		Pager pager = dkBillInfoService.searchListPage(page);//this.dkBillInfoService.searchListPage(page);
		List<DkBillInfoVO> list = (List<DkBillInfoVO>) pager.getResultList();
		ListPageVO<DkBillInfoVO> listPage = new ListPageVO<DkBillInfoVO>(list, pager.getTotalCount());
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		BaseLogUtils.newLogger("新增对象").setLogOperType(LogOperEnum.REQ).setKeys("add",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");

		String ruleId = request.getParameter("ruleId");//垫款规则id
		if(StringUtils.isEmpty(ruleId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("垫付规则没有数据");
			return result;
		}
		
		DkRuleInfoVO ruleInfo = this.dkRuleInfoService.selectById(Long.valueOf(ruleId));
		if(ruleInfo == null){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("垫付规则没有数据");
			return result;
		}
		
		/**
		 * 1、垫付规则 作废了-不能生成
		 */
		if("0".equals(ruleInfo.getRuleStsCd())){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("垫付规则已作废了");
			return result;
		}
		/**
		 *  2、生成垫付单：
		 *  	A、没有垫付单 -生成
		 *  	B、结束后 -生成
		 */
		DkBillInfoDTO dto = this.dkBillInfoService.queryBillInfoByRuleId(new Long(ruleId));
		boolean isinserBill = true;
		if(dto != null && "1".equals(dto.getBillStsCd())){
			isinserBill = false;
			result.setInfo("存在正在执行垫款单，请完成后再行作废");
		}
		
		if(!isinserBill){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result;
		}
		
		DkBillInfoVO entity = null;
		try {
			entity = new DkBillInfoVO();
			entity.setRuleId(Long.valueOf(ruleId));
			Long cmmSeqNextVal = dkQuestneLogApiService.getCmmSeqNextVal();
			entity.setBillNm(ruleInfo.getRuleNm() + "-" + cmmSeqNextVal);
			entity.setRuleNm(ruleInfo.getRuleNm());
			entity.setRefPrjId(ruleInfo.getRefPrjId());
			entity.setRefPrjNm(ruleInfo.getRefPrjNm());
			entity.setBillStsCd(DkBillInfoConstant.BILL_STS_CD_DKZ);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
			Long id = this.dkBillInfoService.add(entity);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setData(id);
			BaseLogUtils.newLogger("新增数据").setLogOperType(LogOperEnum.REQ).setKeys("add","DkBillInfoVO="+ JSONObject.toJSONString(entity),this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

			// 修改规则状态 
			DkRuleInfoVO ruleInfoVO = null;
			ruleInfoVO = new DkRuleInfoVO();
			ruleInfoVO.setId(Long.valueOf(ruleId));
			ruleInfoVO.setBillStsCd(DkBillInfoConstant.BILL_STS_CD_DKZ);
			this.dkRuleInfoService.modify(ruleInfoVO);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("新增对象失败").setLogOperType(LogOperEnum.REQ).setKeys("add",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newLogger("新增对象失败").setLogOperType(LogOperEnum.REQ).setKeys("add",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		BaseLogUtils.newLogger("修改对象").setLogOperType(LogOperEnum.REQ).setKeys("modify",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			BaseLogUtils.newLogger("修改数据,主键不存在").setLogOperType(LogOperEnum.REQ).setKeys("modify",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
			return result;
		}
		DkBillInfoVO entity = null;
		try {
			entity = dkBillInfoService.selectById(Long.valueOf(id));
			entity.setId(Long.valueOf(id));
			entity.setBillStsCd(DkBillInfoConstant.BILL_STS_CD_JS);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfUsrNm(CurrentThreadContext.getCurrentUserName());
			boolean success = this.dkBillInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
				BaseLogUtils.newLogger("修改失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","DkBillInfoVO="+JSONObject.toJSONString(entity),CurrentThreadContext.getCurrentUserName()).info();
			}
			BaseLogUtils.newLogger("修改成功").setLogOperType(LogOperEnum.REQ).setKeys("modify","DkBillInfoVO="+JSONObject.toJSONString(entity),CurrentThreadContext.getCurrentUserName()).info();

			// 修改规则状态 
			DkBillInfoVO billInfoVO = this.dkBillInfoService.selectById(entity.getId());
			DkRuleInfoVO ruleInfoVO = null;
			ruleInfoVO = new DkRuleInfoVO();
			ruleInfoVO.setId(billInfoVO.getRuleId());
			ruleInfoVO.setBillStsCd(DkBillInfoConstant.BILL_STS_CD_JS);
			this.dkRuleInfoService.modify(ruleInfoVO);
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("修改对象失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newLogger("修改对象失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		}
		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		BaseLogUtils.newLogger("移除对象").setLogOperType(LogOperEnum.REQ).setKeys("remove",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		try {
			this.dkBillInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.newLogger("删除数据").setLogOperType(LogOperEnum.REQ).setKeys("removeById","id="+id,this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("移除对象失败").setLogOperType(LogOperEnum.REQ).setKeys("removeById","主键id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newLogger("移除对象失败").setLogOperType(LogOperEnum.REQ).setKeys("removeById","主键id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		BaseLogUtils.newLogger("根据主键获取对象").setLogOperType(LogOperEnum.REQ).setKeys("getById",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			BaseLogUtils.newLogger("获取数据,主键不存在").setLogOperType(LogOperEnum.REQ).setKeys("getById",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
			return result;
		}
		
		try {
			DkBillInfoVO vo = this.dkBillInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
				BaseLogUtils.newLogger("获取数据,数据不存在").setLogOperType(LogOperEnum.REQ).setKeys("getById","id="+id,this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
			}
			result.setData(vo);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("根据主键获取对象失败").setLogOperType(LogOperEnum.REQ).setKeys("getById","主键id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newLogger("根据主键获取对象失败").setLogOperType(LogOperEnum.REQ).setKeys("getById","主键id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
		}

		return result;
	}
	
	/**
	 * 根据规则id 查询垫付单信息 
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/queryBillInfoByRuleId.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object queryBillInfoByRuleId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ruleId = request.getParameter("ruleId");
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(ruleId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result;
		}
		
		try {
			DkBillInfoDTO dto = this.dkBillInfoService.queryBillInfoByRuleId(new Long(ruleId));
			if(dto!=null){
				if("0".equals(dto.getBillStsCd())){// 结束就是已执行
					result.setSuccess(BaseConstant.IS_YESNO_YES);
				}else{
					result.setSuccess(BaseConstant.IS_YESNO_NO);
				}
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
			}
		}catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
		}
		
		return result;
	}
	
}

